package com.zlsy.secondtime.threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * @author zhouliang
 * @date 2020/5/17 11:34
 * <p>
 * 3个线程，线程1和线程2首先被阻塞，线程3唤醒他们，notify、notifyAll
 * start先执行并不代表线程先启动
 */
public class WaitNotifyAll implements Runnable {

    private static final Object LOCK = new Object();

    @Override
    public void run() {
        synchronized (LOCK) {
            System.out.println(Thread.currentThread().getName() + " got lock!");
            try {
                System.out.println(Thread.currentThread().getName() + " Will enter waiting！");
                LOCK.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " Wake up, over..");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll r = new WaitNotifyAll();
        Thread a = new Thread(r);
        a.setName("线程A");
        Thread b = new Thread(r);
        b.setName("线程B");

        Thread c = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (LOCK) {
                    System.out.println(Thread.currentThread().getName() + " notifyAll thread！");
//                    LOCK.notifyAll();
                    LOCK.notify();
                }
            }
        });
        c.setName("线程C");

        a.start();
        b.start();
        Thread.sleep(1000);
        c.start();

    }
}
